/**
 * @file wndproc.c
 * @author Yao Zongyou <yaozy2010@gmail.com>
 * @date 2011-03-26
 */

#include "master.h"

#include "wndproc.h"
#include "stream.h"
#include "misc.h"
#include "gui.h"
#include "flags.h"

LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
	static short sOptions = 0;
	static HBRUSH hbrBackBrush = NULL;

	switch (msg) {
		case WM_COMMAND:
			switch (LOWORD(wParam)) {
				case IDI_FILE_OPEN:
//					if (pGraph != NULL) {
//						SendMessage(hwnd, WM_COMMAND, MAKEWPARAM(IDI_FILE_CLOSE, 0), (LPARAM)NULL);
//					}
					GetOpenFile(hwnd, sOptions & IS_TRAYED);
					break;
				case IDI_FILE_EXIT:
					SendMessage(hwnd, WM_CLOSE, 0, 0);
					break;
				case IDI_FILE_TOGGLESHORTCUT:
					ToggleDesktopLink();
					break;
				case IDI_FILE_MINTOTRAY:
					if (sOptions & TRAY_MINIMIZE) {
//						MenuCheck(hwnd, FILE_MENU, IDI_FILE_MINTOTRAY, false);
						sOptions &= (~(TRAY_MINIMIZE));
					} else {
//						MenuCheck(hwnd, FILE_MENU, IDI_FILE_MINTOTRAY, true);
						sOptions |= TRAY_MINIMIZE;
					}
					break;
				case IDI_HELP_ABOUT:
					CreateDialog(GetModuleHandle(NULL), MAKEINTRESOURCE(ID_ABOUT), hwnd, (DLGPROC)AboutDlgProc);
					break;
			}
			break;

		case WM_CREATE: {
			HMENU hMenu = GetMenu(hwnd);
//			HMENU hToolsMenu = GetSubMenu(hMenu, TOOLS_MENU);
			hbrBackBrush = GetSysColorBrush(COLOR_WINDOW);
//			if (bCmdLine == false) {
//				ReadOptionsAndConfigure(hwnd, &sOptions);
//			}
			ShutdownPrivilege();
			ControlCreate(hwnd);

//			if (AreTypesRegistered() == true) {
//				EnableMenuItem(hToolsMenu, IDI_TOOLS_UNREGISTER, MF_ENABLED);
//			} else {
//				EnableMenuItem(hToolsMenu, IDI_TOOLS_REGISTER, MF_ENABLED);
//			}

//			CheckAndFixOpenWith();

			break;
		}
		case WM_CTLCOLORSTATIC:
		case WM_CTLCOLORBTN:
		case WM_CTLCOLORLISTBOX: {
			HDC hdcStatic = (HDC)wParam;
			SetBkMode(hdcStatic, TRANSPARENT);
			return (LRESULT)hbrBackBrush;
		}
		case WM_PAINT: {
			HDC hdc = NULL;
			PAINTSTRUCT ps = {0};
			RECT rc = {0};

			GetClientRect(hwnd, &rc);

			hdc = BeginPaint(hwnd, &ps);
			FillRect(hdc, &rc, hbrBackBrush);
			EndPaint(hwnd, &ps);
			break;
		}
		case WM_DESTROY:
			PostQuitMessage(0);
			break;
		default:
			return DefWindowProc(hwnd, msg, wParam, lParam);
	}
	
	return 0;
}

bool CALLBACK AboutDlgProc(HWND hDialog, UINT Message, WPARAM wParam, LPARAM lParam)
{
	static HMODULE hAudioPlayer = NULL;
	switch (Message) {
		case WM_INITDIALOG:
			hAudioPlayer = GetModuleHandle(NULL);
			return true;
		case WM_COMMAND:
			switch (LOWORD(wParam)) {
				case IDOK:
					DestroyWindow(hDialog);
					break;
			}
			break;
		case WM_PAINT: {
			PAINTSTRUCT ps = {0};
			WNDCLASS wc = {0};
			HDC hdc = BeginPaint(hDialog, &ps);
			GetClassInfo(hAudioPlayer, TEXT("AudioPlayer"), &wc);
			DrawIconEx(hdc, 295, 35, wc.hIcon, 0, 0, 0, NULL, DI_DEFAULTSIZE | DI_NORMAL);
			EndPaint(hDialog, &ps);
			return false;
		}
		default:
			return false;
	}

	return true;
}
